package com.android.place360.services;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.util.Log;


public class HttpService {
		
	public static String SendRequest(String url) {
		String rdata = "";
		try {
			// System.setProperty("http.keepAlive", "false");
			InputStream is = null;
			URL myFileUrl = new URL(url);

			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("GET");
			conn.connect();
			is = conn.getInputStream();
			int code = conn.getResponseCode();

			if (code == HttpURLConnection.HTTP_OK) { // HTTP_OK=200
				if (is != null) {
					ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
					int len = -1;
					byte[] buff = new byte[1024];
					while ((len = is.read(buff)) != -1) {
						outputStream.write(buff, 0, len);
					}
					byte[] bs = outputStream.toByteArray();
					rdata = new String(bs);
					is.close();
					conn.disconnect();
					outputStream.flush();
					outputStream.close();
				}
			} else if (code == -1) {
				is.close();
				conn.disconnect();
				SendRequest(url);
			} else {
				throw new Exception("Please check Internet connection:" + code);
			}
			conn.disconnect();
		} catch (Exception e) {
			Log.i("Error", "Error from HttpConnection: "+e.getMessage());
		}
		return rdata;
	}

	public static InputStream OpenHttpConnection(String urlString)
			throws IOException {
		InputStream in = null;
		int response = -1;
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		if (!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");
		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("POST");
			httpConn.connect();
			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (Exception ex) {
			throw new IOException("Error connecting");
		}
		return in;
	}

}
